import os
from openpyxl import load_workbook, Workbook
from DataSheetClass import Sheet, DataSheet
from DataInterfaceClass import DataInterface


class XlsxDatas(DataInterface):
    def __init__(self, datasheet:DataSheet):
        super().__init__(datasheet=datasheet)
        
    def read_source(self):
        if not (self.datasheet.source_file_path and os.path.exists(self.datasheet.source_file_path)):
            raise ValueError("No filename provided, cannot read")
        self.datasheet.clearSheets()        
        filepath = self.datasheet.source_file_path
        try:
            workbook = load_workbook(filepath)
            for sheet_name in workbook.sheetnames:
                worksheet = workbook[sheet_name]
                sheet = Sheet(name=sheet_name)
                for row in worksheet.iter_rows(values_only=True):
                    sheet.append_row(list(row))
                self.datasheet.append_sheet(sheet)
            self.datasheet.set_current_sheet_by_index(0)
        except Exception as e:
            raise ValueError(f"Failed to read file: {filepath}->{e}")

    def update_source(self):
        if not (self.datasheet.source_file_path):
            raise ValueError("No filename provided, cannot save")
        filepath = self.datasheet.source_file_path    
        try:
            workbook = Workbook()
            for sheet in self.datasheet.Sheets:
                ws = workbook.create_sheet(title=sheet.name)
                for row in sheet.rows:
                    ws.append(row)
            workbook.save(filepath)
        except Exception as e:
            raise ValueError(f"Failed to save file: {filepath}->{e}")
        



if __name__ == "__main__":
    xlsxd = DataSheet("1.xlsx")
    xlsxdata = XlsxDatas(xlsxd)
    xlsxdata.read_source()
    newsheet = Sheet("newsheet2")
    newsheet.append_row([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27])
    xlsxdata.datasheet.append_sheet(newsheet)
    
    
    xlsxd2 = DataSheet.Copy(xlsxd)
    xlsxd2.source_file_path = "2.xlsx"
    xlsxdata2 = XlsxDatas(xlsxd2)
    
    xlsxdata2.update_source()
    
    
    


